package com.fone.player.activity.search.adapter;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.search.SearchActivity;
import com.fone.player.activity.search.SearchResultActivity;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.SearchRst;
import com.fone.player.client.SearchRst.Cnt;
import com.fone.player.client.SearchRst.Cnts;
import com.fone.player.client.SearchRst.Srhcnt;
import com.fone.player.play.FonePlayerActivity;
import com.fone.player.play.PlayerAction;
import com.fone.player.play.PlayerFrom;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.widget.xlistview.XListView;
import com.fone.player.widget.xlistview.XListView.IXListViewListener;

public class SearchResultViewPagerAdapter extends PagerAdapter implements OnClickListener, IXListViewListener, OnItemClickListener {

	private static final String TAG = "SearchResultViewPagerAdapter";

	// private List<View> viewList;
	private List<String> mTitles;

	private View search_result_video_view;
	private View search_result_all_view;
	private View rl_web_search;
	private View rl_web_search_all;
	private XListView lv_search_result_video;
	private XListView lv_search_result_all;
	private View rl_no_result;
	private View rl_no_search_result_all;

	private SearchResultAdapter mVideoAdapter;
	private ListViewAdapter mAllAdapter;

	private SearchRst searchRst;
	private Srhcnt mediaSrhcnt;// 影视剧搜索结果类
	private Srhcnt allSrhcnt;// 综合视频搜索结果类

	private List<Cnt> mVideoList, mAllList; // 分别为影视剧集合和综合集合

	private boolean videoOver = false;
	private boolean allOver = false;

	private String encodeKw = null;

	private int searchType = 3;

	public SearchResultViewPagerAdapter() {
		iniViews();
	}

	/**
	 * 初始化views
	 */
	private void iniViews() {

		// 初始化 标头
		mTitles = new ArrayList<String>();
		mTitles.add("影视剧");
		mTitles.add("综合视频");

		// 初始化views

		search_result_video_view = LayoutInflater.from(ApplicationManage.getGlobalContext()).inflate(R.layout.search_result_video_view, null);
		search_result_all_view = LayoutInflater.from(ApplicationManage.getGlobalContext()).inflate(R.layout.search_result_all_view, null);

		rl_web_search = search_result_video_view.findViewById(R.id.rl_web_search);
		rl_web_search_all = search_result_all_view.findViewById(R.id.rl_web_search_all);
		rl_web_search.setOnClickListener(this);
		rl_web_search_all.setOnClickListener(this);

		rl_no_result = search_result_video_view.findViewById(R.id.rl_no_search_result);
		rl_no_search_result_all = search_result_all_view.findViewById(R.id.rl_no_search_result_all);
		rl_no_result.setVisibility(View.GONE);
		rl_no_search_result_all.setVisibility(View.GONE);

		lv_search_result_video = (XListView) search_result_video_view.findViewById(R.id.lv_search_result_video);
		lv_search_result_all = (XListView) search_result_all_view.findViewById(R.id.lv_search_result_all);

		lv_search_result_video.setXListViewListener(this);
		lv_search_result_all.setXListViewListener(this);

		mVideoList = new ArrayList<Cnt>();
		mAllList = new ArrayList<Cnt>();
		mVideoAdapter = new SearchResultAdapter(mVideoList);
		mAllAdapter = new ListViewAdapter(mAllList);

		lv_search_result_video.setAdapter(mVideoAdapter);
		lv_search_result_all.setAdapter(mAllAdapter);
		lv_search_result_all.setOnItemClickListener(this);

		lv_search_result_video.setPullRefreshEnable(false);
		lv_search_result_all.setPullRefreshEnable(false);
		
		setXlistViewDrag(lv_search_result_video, false);
		setXlistViewDrag(lv_search_result_all, false);

		// viewList = new ArrayList<View>();
		// viewList.add(search_result_video_view);
		// viewList.add(search_result_all_view);

	}

	/**
	 * 搜索
	 * 
	 * @param keyWord
	 *            关键字
	 * @param SearchType
	 *            搜索类型
	 */
	public void doSearch(String keyWord, int searchType) {

		this.searchType = searchType;

		rl_no_result.setVisibility(View.GONE);
		rl_no_search_result_all.setVisibility(View.GONE);
		String kw = FoneUtil.Base64Encode(keyWord);

		try {
			encodeKw = URLEncoder.encode(kw, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			L.e(TAG, "doSearch", "URLEncoder.encode run error!");
			e.printStackTrace();

		}

		Request.getSearchInstance(ApplicationManage.getGlobalContext()).search(searchType, encodeKw, 1, "0", "0", "0", null, new SearchResultCallBack(false));
		SearchResultActivity.mSearchType = searchType;

	}

	@Override
	public CharSequence getPageTitle(int position) {
		return mTitles.get(position);
	}

	@Override
	public int getCount() {
		return mTitles.size();
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {

		if (position == 0) {
			container.removeView(search_result_video_view);
		} else if (position == 1) {
			container.removeView(search_result_all_view);
		}

		super.destroyItem(container, position, object);
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {

		if (position == 0) {
			container.addView(search_result_video_view);
			return search_result_video_view;
		} else if (position == 1) {
			container.addView(search_result_all_view);
			return search_result_all_view;
		}

		return super.instantiateItem(container, position);
	}

	@Override
	public int getItemPosition(Object object) {
		return super.getItemPosition(object);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.rl_web_search:
		case R.id.rl_web_search_all:
			// TODO 点击了全网搜索
			if(SearchResultActivity.searchResultActivity!=null){
				SearchResultActivity.searchResultActivity.doWebSearch();
			}
			break;

		default:
			break;
		}
	}

	// 访问网络回调
	private class SearchResultCallBack implements Callback<SearchRst> {

		private boolean isLoadMore = false;

		public SearchResultCallBack(boolean isLoadMore) {
			this.isLoadMore = isLoadMore;
		}

		@Override
		public void onSuccess(SearchRst t) {
			L.i(TAG, "SearchResultCallBack:  success");
			L.i(TAG, "SearchRst:" + t.toString());
			if (SearchResultActivity.searchResultActivity != null) {
				SearchResultActivity.searchResultActivity.mHandler.obtainMessage(SearchResultActivity.CANCLE_WAITING).sendToTarget();
				if (t.result == 0) {
					if (!isLoadMore) {
						if(SearchResultActivity.searchResultActivity!=null&&SearchResultActivity.searchResultActivity.mViewPager!=null){
							SearchResultActivity.searchResultActivity.mViewPager.setCurrentItem(0);
						}
						mVideoList.clear();
						mAllList.clear();
						mVideoAdapter.notifyDataSetChanged();
						mAllAdapter.notifyDataSetChanged();
					}
					if(SearchResultActivity.searchResultActivity != null){
						fillData(t);
					}
					searchRst = t;
				} else {
					rl_no_result.setVisibility(View.VISIBLE);
					lv_search_result_video.setVisibility(View.GONE);
					rl_no_search_result_all.setVisibility(View.VISIBLE);
					lv_search_result_all.setVisibility(View.GONE);
					FoneUtil.showToast(ApplicationManage.getGlobalContext(), "信息获取失败，请重新搜索");
				}
			}
		}

		@Override
		public void onFailure(Error error) {
			if (SearchResultActivity.searchResultActivity != null) {
				SearchResultActivity.searchResultActivity.mHandler.obtainMessage(SearchResultActivity.CANCLE_WAITING).sendToTarget();
				lv_search_result_all.setEnableDragLoadMore(true);
				lv_search_result_video.setEnableDragLoadMore(true);
				rl_no_result.setVisibility(View.VISIBLE);
				lv_search_result_video.setVisibility(View.GONE);
				rl_no_search_result_all.setVisibility(View.VISIBLE);
				lv_search_result_all.setVisibility(View.GONE);
				FoneUtil.showToast(ApplicationManage.getGlobalContext(), "信息获取失败，请重新搜索");
				L.i(TAG, "SearchResultCallBack:  " + "error.status:" + error.getStatus());
				L.i(TAG, "SearchResultCallBack:  " + "error.reason:" + error.getReason());
			}
		}

	}

	// 填充服务器返回来的数据
	public void fillData(SearchRst t) {

		if (t.srhcnts == null || t.srhcnts.srhcntList == null) {
			L.i(TAG, "t.srhcnts或t.srhcnts.srhcntList is null!");
			return;
		}
		List<Srhcnt> srhcntList = t.srhcnts.srhcntList;
		String shost = t.shost;
		L.i(TAG, "SearchResultCallBack: srhcntList size:" + srhcntList.size());
		if (srhcntList.size() == 0 || srhcntList == null) {// 搜索内容为空

			if (mVideoList == null || (mVideoList != null && mVideoList.size() == 0)) {
				rl_no_result.setVisibility(View.VISIBLE);
			}
			if (mAllList == null || (mAllList != null && mAllList.size() == 0)) {
				rl_no_search_result_all.setVisibility(View.VISIBLE);
			}
			setXlistViewDrag(lv_search_result_all, false);
			setXlistViewDrag(lv_search_result_video, false);
			return;
		} else {
			rl_no_result.setVisibility(View.GONE);
			rl_no_search_result_all.setVisibility(View.GONE);
			lv_search_result_video.setVisibility(View.VISIBLE);
			lv_search_result_all.setVisibility(View.VISIBLE);

			for (int i = 0; i < srhcntList.size(); i++) {
				Srhcnt srhcnt = srhcntList.get(i);

				Cnts cnts = srhcnt.cnts;
				List<Cnt> cntList = cnts.cntList;
				if (srhcnt.type == 0) {
					mediaSrhcnt = srhcnt;
					L.i(TAG, "SearchResultCallBack:  mediaSrhcnt current page:" + mediaSrhcnt.rp.p);
					if (cntList != null && cntList.size() >= 18) {
						setXlistViewDrag(lv_search_result_video, true);
					} else {
						if (cntList == null || cntList.size() == 0) {
							if (mVideoList.size() > 0 && !videoOver && SearchResultActivity.searchResultActivity.mCurrentPageID == SearchResultActivity.searchResultActivity.MEDIAPAGE) {
								FoneUtil.showToast(ApplicationManage.getGlobalContext(), "已经是最后一页");
							}
							videoOver = true;// video资源加载完毕
						}
						setXlistViewDrag(lv_search_result_video, false);
					}
				} else if (srhcnt.type == 1) {
					allSrhcnt = srhcnt;
					L.i(TAG, "SearchResultCallBack:  allSrhcnt current page:" + allSrhcnt.rp.p);
					if (cntList != null && cntList.size() >= 18) {
						setXlistViewDrag(lv_search_result_all, true);
					} else {
						if (cntList == null || cntList.size() == 0) {
							if (mAllList.size() > 0 && !allOver && SearchResultActivity.searchResultActivity.mCurrentPageID == SearchResultActivity.searchResultActivity.ALLPAGE) {
								FoneUtil.showToast(ApplicationManage.getGlobalContext(), "已经是最后一页");
							}
							allOver = true;// 综合视频加载完毕
						}
						setXlistViewDrag(lv_search_result_all, false);
					}
				}

				if (cntList == null) {
					L.i(TAG, "SearchResultCallBack: cntList is null");
					continue;
				}
				L.i(TAG, "SearchResultCallBack: cntList size:" + cntList.size());
				for (int j = 0; j < cntList.size(); j++) {
					Cnt cnt = cntList.get(j);
					L.i(TAG, "SearchResultCallBack:   cnt :" + cnt.toString());

					cnt.pic1 = cnt.pic1.replace("[shost]", shost);
					cnt.pic2 = cnt.pic2.replace("[shost]", shost);
					L.i(TAG, "SearchResultCallBack:   cnt.pic1 :" + cnt.pic1);
					if (srhcnt.type == 0) {
						mVideoList.add(cnt);
					} else if (srhcnt.type == 1) {
						mAllList.add(cnt);
					}
				}
			}
			if (mVideoList.size() == 0) {
				rl_no_result.setVisibility(View.VISIBLE);
				lv_search_result_video.setVisibility(View.GONE);
			} else {
				rl_no_result.setVisibility(View.GONE);
				lv_search_result_video.setVisibility(View.VISIBLE);

			}
			if (mAllList.size() == 0) {
				rl_no_search_result_all.setVisibility(View.VISIBLE);
				lv_search_result_all.setVisibility(View.GONE);
			} else {
				rl_no_search_result_all.setVisibility(View.GONE);
				lv_search_result_all.setVisibility(View.VISIBLE);

			}
			mVideoAdapter.notifyDataSetChanged();
			mAllAdapter.notifyDataSetChanged();
		}
	}

	private void setXlistViewDrag(XListView xListview, boolean canDrag) {
		xListview.stopLoadMore();
		xListview.setPullLoadEnable(canDrag);
		xListview.setEnableDragLoadMore(canDrag);
	}

	private void doMoreSearch(Srhcnt srhcnt) {
		if (srhcnt != null && srhcnt.rp != null) {
			int page = srhcnt.rp.p;
			if (searchRst != null && searchRst.dramaindex != null && searchRst.zhindex != null) {
				Request.getSearchInstance(ApplicationManage.getGlobalContext()).search(searchType, encodeKw, page, "0", searchRst.dramaindex, searchRst.zhindex, null, new SearchResultCallBack(true));

				lv_search_result_all.setEnableDragLoadMore(false);
				lv_search_result_video.setEnableDragLoadMore(false);

				// setXlistViewDrag(lv_search_result_all, false);
				// setXlistViewDrag(lv_search_result_video, false);
			}
		} else {
			L.i(TAG, "doMoreSearch has null");
		}
	}

	@Override
	public void onRefresh() {
	}

	@Override
	public void onLoadMore() {

		// 需要区分影视剧和综合视频的加载
		if (SearchResultActivity.searchResultActivity.mCurrentPageID == SearchResultActivity.searchResultActivity.MEDIAPAGE) {
			doMoreSearch(mediaSrhcnt);
		} else if (SearchResultActivity.searchResultActivity.mCurrentPageID == SearchResultActivity.searchResultActivity.ALLPAGE) {
			doMoreSearch(allSrhcnt);
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub

		if (FoneUtil.isNetOkWithToast(ApplicationManage.getGlobalContext())) {
			if(position - 1>mAllList.size()){
				return;
			}
			Cnt cnt = mAllList.get(position - 1);
			String url = cnt.url;
			L.i(TAG, "all  video url:" + url);
			Intent intent = new Intent(ApplicationManage.getGlobalContext(), FonePlayerActivity.class);
			L.i(TAG, "mSearchType:" + searchType);
//			if (searchType == SearchActivity.SEARCH_HOT_WORD) {
//				intent.putExtra("from", PlayerFrom.SEARCH_ENTRANCE);
//			} else {
				intent.putExtra("from", PlayerFrom.SEARCH_NORMAL);
//			}
			if (1 == cnt.utp) {
				intent.putExtra("action", PlayerAction.DETAIL.name());
				intent.putExtra("vgdetail", url);
			} else {
				intent.putExtra("action", PlayerAction.FULLPLAY.name());
				intent.putExtra("xyzplay", url);
			}
			intent.putExtra("name", cnt.name);
			L.i(TAG, "all  video name:" + cnt.name);
			if (SearchResultActivity.searchResultActivity != null) {
				SearchResultActivity.searchResultActivity.startActivity(intent);
			}
		}
	}

	public void removeData() {
		mVideoAdapter.removeData();
		mAllAdapter.removeData();
//		mAllAdapter = null;
//		mVideoAdapter = null;
//		mVideoList = null;
//		mAllList = null;
		lv_search_result_video.removeAllViewsInLayout();
		lv_search_result_all.removeAllViewsInLayout();
//		lv_search_result_video = null;
//		lv_search_result_all = null;
//		search_result_video_view = null;
//		search_result_all_view = null;
	}
}
